package com.yyaccp.appinfo.controller;

import com.yyaccp.appinfo.domain.AppInfo;
import com.yyaccp.appinfo.domain.AppVersion;
import com.yyaccp.appinfo.domain.DevUser;
import com.yyaccp.appinfo.exception.LoginException;
import com.yyaccp.appinfo.service.AppInfoService;
import com.yyaccp.appinfo.service.AppVersionService;
import com.yyaccp.appinfo.service.DevUserService;
import com.yyaccp.appinfo.service.SmsService;
import com.yyaccp.appinfo.utils.AjaxResult;
import com.yyaccp.appinfo.utils.Constants;
import com.yyaccp.appinfo.utils.ExcelUtils;
import com.yyaccp.appinfo.utils.RandomUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api")
public class DevUserController {

    @Autowired
    private DevUserService devUserService;
    @Autowired
    private AppInfoService appInfoService;
    @Autowired
    private AppVersionService appVersionService;
    @Autowired
    private SmsService smsService;

    @PostMapping("/login")
    public AjaxResult login(DevUser User, HttpSession session){
        try{
            DevUser devUser = devUserService.devLogin(User);
            devUser.setDevPassword("******");
            session.setAttribute(Constants.DEV_USER_SESSION,devUser);
            return AjaxResult.success(devUser);
        }catch (LoginException ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    @RequestMapping("/out")
    public AjaxResult out(HttpSession session){
        session.invalidate();
        return AjaxResult.success();
    }

    @RequestMapping("/Add")
    public AjaxResult Add(AppInfo appInfo, MultipartFile file1, HttpServletRequest request){
        if(file1 != null){
            String path = request.getServletContext().getRealPath("/files");
            String prefix = FilenameUtils.getExtension(file1.getOriginalFilename());
            try {
                String NewfileName = System.currentTimeMillis()+"_Personal."+prefix;
                File file = new File(path, NewfileName);
                file1.transferTo(file);
                String fileName = "files"+File.separator+NewfileName;
                appInfo.setLogoLocPath(file.getAbsolutePath());
                appInfo.setLogoPicPath(fileName);
            }catch(IOException ex){
                return AjaxResult.error(ex.getMessage());
            }
        }
        if(appInfoService.Add(appInfo)>0){
            return AjaxResult.success(appInfo);
        }else{
            return AjaxResult.error();
        }

    }

    @RequestMapping("/selectId")
    public AjaxResult selectId(Long id){
        AppInfo appInfo = appInfoService.selectId(id);
        if(appInfo != null){
            return AjaxResult.success(appInfo);
        }else{
            return AjaxResult.error();
        }
    }

    @RequestMapping("/update")
    public AjaxResult update(AppInfo appInfo,MultipartFile file1,HttpServletRequest request){
        if(file1 != null){
            String path = request.getServletContext().getRealPath("/files");
            String prefix = FilenameUtils.getExtension(file1.getOriginalFilename());
            try {
                String NewfileName = System.currentTimeMillis()+"_Personal."+prefix;
                File file = new File(path, NewfileName);
                file1.transferTo(file);
                String fileName = "files"+File.separator+NewfileName;
                appInfo.setLogoLocPath(file.getAbsolutePath());
                appInfo.setLogoPicPath(fileName);
            }catch(IOException ex){
                return AjaxResult.error(ex.getMessage());
            }
        }
        if(appInfoService.update(appInfo)>0){
            return AjaxResult.success(appInfo);
        }else{
            return AjaxResult.error();
        }
    }

    @RequestMapping("/selectVersionAppId")
    public AjaxResult selectVersionAppId(AppVersion appVersion){
        List<AppVersion> appVersionList = appVersionService.selectAppId(appVersion);
        if(appVersionList != null){
            return AjaxResult.success(appVersionList);
        }else{
            return AjaxResult.error();
        }
    }

    @RequestMapping("/selectVersionId")
    public AjaxResult selectVersionId(AppVersion appVersion){
        AppVersion version = appVersionService.selectByPrimaryKey(appVersion);
        if(version != null){
            return AjaxResult.success(version);
        }else{
            return AjaxResult.error();
        }
    }

    @RequestMapping("/addVersion")
    public AjaxResult addVersion(AppVersion appVersion,MultipartFile file1,HttpServletRequest request) {
        if (file1 != null) {
            String path = request.getServletContext().getRealPath("/files");
            System.out.println(path);
            String prefix = FilenameUtils.getExtension(file1.getOriginalFilename());
            try {
                String NewfileName = System.currentTimeMillis() + "_Personal." + prefix;
                File file = new File(path, NewfileName);
                file1.transferTo(file);
                String fileName = "files" + File.separator + NewfileName;
                appVersion.setDownloadLink(fileName);
                appVersion.setApkFileName(NewfileName);
                appVersion.setApkLocPath(file.getAbsolutePath());
            } catch (IOException ex) {
                return AjaxResult.error(ex.getMessage());
            }
        }
        if (appVersion.getId() == null) {
            if (appVersionService.add(appVersion) > 0) {
                Long versionId = appVersionService.selectNewVersion(appVersion);
                appVersion.setId(versionId);
                if (appInfoService.updateVersion(appVersion) > 0) {
                    return AjaxResult.success(appVersion);
                } else {
                    return AjaxResult.error();
                }
            } else {
                return AjaxResult.error();
            }
        }else{
            if(appVersionService.updateByPrimaryKey(appVersion)>0){
                return AjaxResult.success(appVersion);
            }else{
                return AjaxResult.error();
            }
        }
    }

    @RequestMapping("/delete")
    public AjaxResult delete(Long id){
        AppVersion appVersion = new AppVersion();
        AppInfo appInfo = appInfoService.selectId(id);
        appVersion.setAppId(id);
        appInfo.setId(id);
        List<AppVersion> versions = appVersionService.selectAppId(appVersion);
        for(AppVersion version : versions){
            if(version.getApkLocPath() != null && !version.getApkLocPath().equals("")){
                File file = new File(version.getApkLocPath());
                if(file.exists()){
                    file.delete();
                }
            }
            appVersionService.deleteAppId(id);
        }
        File file1 = new File(appInfo.getLogoLocPath());
        if(file1.exists()){
            file1.delete();
        }
        if(appInfoService.deleteByPrimaryKey(id)>0){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    @RequestMapping("/onSale")
    public AjaxResult onSale(Long status,Long id){
       if(status == 4){
           if(appInfoService.onSale(id)>0){
               return AjaxResult.success("上架成功!");
           }
       }else if(status == 5){
           if(appInfoService.offSale(id)>0){
               return AjaxResult.success("下架成功!");
           }
       }
       return AjaxResult.error();
    }

    @RequestMapping("/exportExcel")
    public AjaxResult exportExcel(){
        try {
            ExcelUtils.export(appInfoService.searchAll());
        }catch (Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
        return AjaxResult.success();
    }

    @RequestMapping("/sendCode")
    public AjaxResult sendCode(String devPhone){
        if(devUserService.findByDevPhone(devPhone) == null){
            return AjaxResult.error("手机号码不存在");
        }
        //发送验证码
        try {
            smsService.sendMessage(devPhone, RandomUtils.random(4));
            return AjaxResult.success();
        }catch(Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @RequestMapping("/loginPhone")
    public AjaxResult LoginPhone(String devPhone,String code,HttpSession session){
        try {
            DevUser devUser = devUserService.login(devPhone, code);
            devUser.setDevPassword("******");
            session.setAttribute(Constants.DEV_USER_SESSION,devUser);
            return AjaxResult.success(devUser);
        }catch(LoginException ex){
            return AjaxResult.error(ex.getMessage());
        }
    }
}
